package com.wj.init.utils;

import lombok.Data;

/**
 * @author wujian
 * @date 2019/8/1 10:53
 * @desc 返回结果文件
 */
@Data
public class Result {

    public static final String SUCCESS = msg(Code.success, "请求成功");
    public static final String PARAM_ERROR = msg(Code.paramError, "参数有误");
    public static final String UNAUTHORIZED = msg(Code.unauthorized, "身份认证失败");
    public static final String FORBIDDEN = msg(Code.forbidden, "无此权限");
    public static final String NOT_FOUND = msg(Code.notFound, "请求失败");
    public static final String ERROR = msg(Code.error, "内部错误");
    public static final String JSON_FAIL = msg(Code.error, "json序列化失败");

    private Integer code;

    private String msg;

    private Object data;

    /**
     * 将实体转换成json
     * @return
     */
    private String toJson() {
        try {
            return Utils.MAPPER.writeValueAsString(this);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON_FAIL;
        }
    }

    /**
     * 带数据返回值
     * @param data 数据
     * @return
     */
    public static String success(Object data) {
        return new Result(Code.success.value, "请求成功", data).toJson();
    }

    /**
     * 自定义异常信息
     * @param msg 异常说明
     * @return
     */
    public static String error(String msg) {
        return new Result(Code.error.value, msg, null).toString();
    }

    /**
     * 返回无数据信息
     * @return
     */
    public static String msg(Code code, String msg) {
        return new Result(code.value, msg, null).toJson();
    }

    /**
     * 添加私有化构造器
     * @param code code
     * @param msg  消息类容
     * @param data 返回数据
     */
    private Result(Integer code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public enum Code {
        //成功
        success(200),
        //异常
        error(500),
        //参数异常
        paramError(400),
        //身份验证失败
        unauthorized(401),
        //无权限
        forbidden(403),
        //请求失败, 不存在
        notFound(404);

        private int value;

        public int getValue() {
            return value;
        }

        Code(int code) {
            this.value = code;
        }

    }

}
